package org.misty.blog.service.impl;

import org.misty.blog.dao.CategoryRepository;
import org.misty.blog.exception.NotFoundException;
import org.misty.blog.po.Category;
import org.misty.blog.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class CategoryServiceImpl implements CategoryService {
    private final CategoryRepository categoryRepository;

    public CategoryServiceImpl(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    @Transactional
    @Override
    public Category saveCategory(Category category) {
        return categoryRepository.save(category);
    }

    @Override
    public Optional<Category> getCategory(Long id) {
        return categoryRepository.findById(id);
    }

    @Override
    public Optional<Category> getCategoryByName(String name) {
        return categoryRepository.findByName(name);
    }

    @Override
    public Page<Category> listCategory(Pageable pageable) {
        return categoryRepository.findAll(pageable);
    }

    @Override
    public List<Category> listCategory() {
        return categoryRepository.findAll();
    }

    @Override
    public List<Category> listTop(int n) {
        Sort sort = Sort.by(Sort.Direction.DESC, "articles.size");
        Pageable pageable = PageRequest.of(0, n, sort);
        return categoryRepository.findTop(pageable);
    }

    @Transactional
    @Override
    public Category updateCategory(Long id, Category category) {
        Optional<Category> old = categoryRepository.findById(id);
        if (!old.isPresent()) {
            throw new NotFoundException("不存在该类型 " + id);
        }
        Category updated = old.get();
        BeanUtils.copyProperties(category, updated);
        return categoryRepository.save(updated);
    }

    @Transactional
    @Override
    public void removeCategory(Long id) {
        categoryRepository.deleteById(id);
    }
}
